// ====== 导入用户频道请求 ======
import { reqChannels, reqAllChannels } from '@/api/channels'
const state = {
  channels: [],
  allChannels: []
}
const mutations = {
  setChannels (state, channels) {
    state.channels = channels
  },
  setAllChannels (state, allChannels) {
    state.allChannels = allChannels
  },
  // 添加频道
  addChannels (state, newChannels) {
    state.channels.push(newChannels)
  },
  // 删除频道
  delChannels (state, channel) {
    // 参数channel是要删除的，要保留与参数channel不一致的（一直的要删除）
    state.channels = state.channels.filter(item => item.id !== channel.id)
  }
}

const actions = {
  // *用户频道
  async getChannelsAsync (context) {
    const { data: { channels } } = await reqChannels()
    // 提交给mutations，将channels里的数据存起来
    context.commit('setChannels', channels)
  },
  // *所有频道
  async getAllChannelsAsync (context) {
    const { data: { channels } } = await reqAllChannels()
    context.commit('setAllChannels', channels)
  }
}
const getters = {
  optionalChannels (state) {
  // 可选频道（optionalChannels）=所有频道（allChannels）-用户频道（channels）
  // filter:函数中保留这一项返回true，否则返回false
  // findindex：找到返回对应项的下标，找不到返回-1
    const result = state.allChannels.filter(item => {
      const index = state.channels.findIndex(mychannels => mychannels.id === item.id)
      return index === -1
    })
    return result
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
